import React, { useState, useEffect, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router-dom';
import { 
  sendMessageToAI, 
  getSuggestedQuestions, 
  getConversationHistory, 
  saveConversation, 
  clearConversationHistory 
} from '../services/aiAssistantService';
import { isTokenConfigured } from '../services/aiConfigService';
import AIConfig from './AIConfig';
import './AIAssistant.css';

const AIAssistant = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const [isOpen, setIsOpen] = useState(false);
  const [message, setMessage] = useState('');
  const [conversation, setConversation] = useState([]);
  const [isTyping, setIsTyping] = useState(false);
  const [suggestedQuestions, setSuggestedQuestions] = useState([]);
  const [showAIConfig, setShowAIConfig] = useState(false);
  const [tokenConfigured, setTokenConfigured] = useState(false);
  const messagesEndRef = useRef(null);
  const inputRef = useRef(null);

  useEffect(() => {
    // Load conversation history and suggested questions
    setConversation(getConversationHistory());
    setSuggestedQuestions(getSuggestedQuestions());
    setTokenConfigured(isTokenConfigured());
  }, []);

  useEffect(() => {
    // Scroll to bottom when conversation updates
    scrollToBottom();
  }, [conversation]);

  useEffect(() => {
    // Focus input when assistant opens
    if (isOpen && inputRef.current) {
      inputRef.current.focus();
    }
  }, [isOpen]);

  const scrollToBottom = () => {
    messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' });
  };

  const handleSendMessage = async () => {
    if (!message.trim()) return;

    const userMessage = {
      role: 'user',
      content: message,
      timestamp: new Date().toISOString()
    };

    // Add user message to conversation
    const updatedConversation = [...conversation, userMessage];
    setConversation(updatedConversation);
    setMessage('');
    setIsTyping(true);

    try {
      // Get recent messages as context (last 10 messages)
      const context = updatedConversation.slice(-10);
      
      // Send message to AI
      const response = await sendMessageToAI(message, context);
      
      // Add AI response to conversation
      const aiMessage = {
        role: 'assistant',
        content: response.message,
        timestamp: response.timestamp,
        success: response.success
      };
      
      const newConversation = [...updatedConversation, aiMessage];
      setConversation(newConversation);
      
      // Save conversation to localStorage
      saveConversation(newConversation);
    } catch (error) {
      console.error('Error sending message to AI:', error);
      
      // Add error message to conversation
      const errorMessage = {
        role: 'assistant',
        content: t('aiAssistant.errorMessage'),
        timestamp: new Date().toISOString(),
        success: false
      };
      
      const newConversation = [...updatedConversation, errorMessage];
      setConversation(newConversation);
      saveConversation(newConversation);
    } finally {
      setIsTyping(false);
    }
  };

  const handleKeyPress = (e) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      handleSendMessage();
    }
  };

  const handleSuggestedQuestion = (question) => {
    setMessage(question);
    inputRef.current?.focus();
  };

  const handleClearConversation = () => {
    if (window.confirm(t('aiAssistant.clearConfirm'))) {
      clearConversationHistory();
      setConversation([]);
    }
  };

  const handleConfigSaved = () => {
    setTokenConfigured(isTokenConfigured());
  };

  const handleNavigateToPage = (page) => {
    navigate(`/${page}`);
    setIsOpen(false);
  };

  const formatTime = (timestamp) => {
    const date = new Date(timestamp);
    return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
  };

  return (
    <div className={`ai-assistant ${isOpen ? 'open' : ''}`}>
      {/* Assistant Button */}
      <button 
        className="ai-assistant-button"
        onClick={() => setIsOpen(!isOpen)}
        aria-label={isOpen ? t('aiAssistant.closeAssistant') : t('aiAssistant.openAssistant')}
      >
        <div className="assistant-avatar">
          <span className="assistant-icon">🤖</span>
          {isOpen ? (
            <span className="assistant-status active">✕</span>
          ) : (
            <span className="assistant-status"></span>
          )}
        </div>
      </button>

      {/* Assistant Window */}
      {isOpen && (
        <div className="ai-assistant-window">
          <div className="assistant-header">
            <div className="assistant-title">
              <span className="assistant-icon">🤖</span>
              <span>{t('aiAssistant.title')}</span>
              {!tokenConfigured && (
                <span className="config-warning" title={t('aiAssistant.tokenNotConfigured')}>
                  ⚠️
                </span>
              )}
            </div>
            <div className="assistant-actions">
              {!tokenConfigured && (
                <button 
                  className="config-btn"
                  onClick={() => setShowAIConfig(true)}
                  title={t('aiAssistant.configureToken')}
                >
                  ⚙️
                </button>
              )}
              <button 
                className="clear-btn"
                onClick={handleClearConversation}
                title={t('aiAssistant.clearConversation')}
              >
                🗑️
              </button>
            </div>
          </div>

          <div className="assistant-messages">
            {conversation.length === 0 ? (
              <div className="welcome-message">
                <div className="assistant-avatar-large">🤖</div>
                <h3>{t('aiAssistant.welcome')}</h3>
                <p>{t('aiAssistant.welcomeMessage')}</p>
                
                {suggestedQuestions.length > 0 && (
                  <div className="suggested-questions">
                    <h4>{t('aiAssistant.suggestedQuestions')}</h4>
                    <div className="question-list">
                      {suggestedQuestions.map((question, index) => (
                        <button
                          key={index}
                          className="question-btn"
                          onClick={() => handleSuggestedQuestion(question)}
                        >
                          {question}
                        </button>
                      ))}
                    </div>
                  </div>
                )}
              </div>
            ) : (
              <>
                {conversation.map((msg, index) => (
                  <div key={index} className={`message ${msg.role}`}>
                    <div className="message-avatar">
                      {msg.role === 'user' ? '👤' : '🤖'}
                    </div>
                    <div className="message-content">
                      <div className="message-text">
                        {msg.content}
                        {!msg.success && (
                          <span className="error-indicator">⚠️</span>
                        )}
                      </div>
                      <div className="message-time">
                        {formatTime(msg.timestamp)}
                      </div>
                    </div>
                  </div>
                ))}
                {isTyping && (
                  <div className="message assistant">
                    <div className="message-avatar">🤖</div>
                    <div className="message-content">
                      <div className="typing-indicator">
                        <span></span>
                        <span></span>
                        <span></span>
                      </div>
                    </div>
                  </div>
                )}
                <div ref={messagesEndRef} />
              </>
            )}
          </div>

          <div className="assistant-input">
            <div className="input-container">
              <input
                ref={inputRef}
                type="text"
                value={message}
                onChange={(e) => setMessage(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder={t('aiAssistant.inputPlaceholder')}
                disabled={isTyping}
              />
              <button
                className="send-btn"
                onClick={handleSendMessage}
                disabled={!message.trim() || isTyping}
              >
                {isTyping ? '⏳' : '➤'}
              </button>
            </div>
            
            {/* Quick Actions */}
            <div className="quick-actions">
              <button onClick={() => handleNavigateToPage('upload')}>
                {t('aiAssistant.uploadPhotos')}
              </button>
              <button onClick={() => handleNavigateToPage('ai')}>
                {t('aiAssistant.generateVideo')}
              </button>
              <button onClick={() => handleNavigateToPage('albums')}>
                {t('aiAssistant.createAlbum')}
              </button>
            </div>
          </div>
        </div>
      )}

      {/* AI Config Modal */}
      {showAIConfig && (
        <AIConfig 
          onClose={() => setShowAIConfig(false)}
          onConfigSaved={handleConfigSaved}
        />
      )}
    </div>
  );
};

export default AIAssistant;